<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%> 
<jsp:include  page="../header.jsp"/> 

		<form>
			<fieldset>
		    	<legend><strong>数据录入</strong></legend>
				<div class="form-inline">
				  	<div class="form-group">
				    	<label>日期：
				    		<input type="text" id="date" name="date" class="form-control" readonly="readonly" placeholder="日期">
				    	</label>
				  	</div>
				  	<div class="form-group">
				    	<label>项目：
				    		<select class="form-control" name="projectId" id="projectId">
				    			<option value="">---请选择项目---</option>
				    			<c:forEach items="${projectList}" var="list" varStatus="s"> 
				    			<option value="${list.id}">${list.project_name}</option>
				    			</c:forEach>
				    		</select>
				    	</label>
				  	</div>

				  	<button type="button" class="btn btn-primary btn-lg" style="float:right" onclick="location.href='${basePath}chart/project'">
						项目/模块管理 
					</button>
			  	</div>
 
  				

			  	<br>

				<table class="table table-striped">
					<thead>
						<tr>
							<th width="120">项目</th>
							<th width="280">模块</th>
							<th width="120">并发用户</th>
							<th width="120">TPS</th>
							<th width="120">响应时间</th>							
							<th width="150">成功请求</th>
							<th width="150">失败请求</th>
							<th width="120">成功率</th>
							<th>失败备注</th>
							<th width="100">
								操作
							</th>
						</tr>
					</thead>
					<tbody id="testRow">

					</tbody>
					<!-- <tr>
						<td><input type="text" class="form-control input-sm" placeholder="项目"></td>
						<td><input type="text" class="form-control input-sm" placeholder="模块"></td>
						<td><input type="number" class="form-control input-sm" placeholder="并发用户"></td>
						<td><input type="number" class="form-control input-sm" placeholder="TPS"></td>
						<td><input type="number" class="form-control input-sm" placeholder="响应时间"></td>
						<td><input type="number" class="form-control input-sm" placeholder="成功率"></td>
						<td><input type="text" class="form-control input-sm" placeholder="成功请求"></td>
						<td><input type="text" class="form-control input-sm" placeholder="失败请求"></td>
						<td>
							<textarea class="form-control input-sm" rows="1"></textarea>
						</td>
						<td>
							<button type="button" class="btn btn-info btn-xs">复制</button>
							<button type="button" class="btn btn-warning btn-xs">移除</button>
						</td>
					</tr>
					<tr>
						<td><input type="text" class="form-control input-sm" placeholder="项目"></td>
						<td><input type="text" class="form-control input-sm" placeholder="模块"></td>
						<td><input type="number" class="form-control input-sm" placeholder="并发用户"></td>
						<td><input type="number" class="form-control input-sm" placeholder="TPS"></td>
						<td><input type="number" class="form-control input-sm" placeholder="响应时间"></td>
						<td><input type="number" class="form-control input-sm" placeholder="成功率"></td>
						<td><input type="text" class="form-control input-sm" placeholder="成功请求"></td>
						<td><input type="text" class="form-control input-sm" placeholder="失败请求"></td>
						<td>
							<textarea class="form-control input-sm" rows="1"></textarea>
						</td>
						<td>
							<button type="button" class="btn btn-info btn-xs">复制</button>
							<button type="button" class="btn btn-warning btn-xs">移除</button>
						</td>
					</tr> -->
					<tr>
						<td colspan="10" align="right">
							<button type="button" id="btnAddOne" class="btn btn-info btn-sm">新增一行</button>
						</td>
					</tr>
				</table>

				<div style="text-align: center;">
					<button type="button" class="btn btn-success btn-lg" id="btnSave">保存入库</button>
					&nbsp;&nbsp;&nbsp;
					<!-- <button type="button" class="btn btn-info btn-lg" id="btnSaveAndPreview">预览统计图表</button> -->
				</div>


			</fieldset>

		</form>


		<br><br><br>


		<div id="chartDiv" style="width:100%; height: 500px;">
			
		</div>

	</div>


	<script type="text/javascript">
		var selectModule;

		function getModuleSelect(projectId, selectId) {
			var html = '<select class="form-control moduleName">';
			var projectId = $('#projectId').val(); 
			$.each(selectModule, function(i) {
				if (selectModule[i].project_id == projectId)  {
					if (selectId && selectId == selectModule[i].id) {
						html += '<option selected value="'+ selectModule[i].id +'">'+ selectModule[i].module_name +'</option>';					
					} else {
						html += '<option value="'+ selectModule[i].id +'">'+ selectModule[i].module_name +'</option>';					
					}
				}
			})
			html += '</select>';	

			return html;
		}

		function checkDate() {
			var dateVal = $('#date').val();
			var projectId = $('#projectId').val();

			if (!dateVal) {
				return false;
			}
			if (!projectId) {
				return false;
			}

			return true;
		}

		function addTableRow(dataId, projectId, projectName, moduleId, moduleName, concurrentUser, tps, responseTime, successRate, successReponse, errorReponse, remark) {
			if (!checkDate()) { 
				layer.alert('日期和项目必须输入', {icon: 5});
				return; 
			}
			if (!projectId) projectId = $('#projectId').val();
			if (!projectName) projectName = $('#projectId').find("option:selected").text();

			var rowHtml = '<tr>';
			rowHtml += '<input type="hidden" class="dataId" value="'+ (dataId ? dataId : '') +'">';
			rowHtml += '<input type="hidden" class="projectId" value="'+ projectId +'">'; 
			// rowHtml += '<td><input type="text" class="form-control input-sm projectName" placeholder="项目" value="'+ (projectName ? projectName : '') +'"></td>';
			rowHtml += '<td><span class="projectName">'+ projectName +'</span></td>';
			// rowHtml += '<td><input type="text" class="form-control input-sm moduleName" placeholder="模块" value="'+ (moduleName ? moduleName : '') +'"></td>';
			rowHtml += '<td>'+ getModuleSelect(projectId, moduleId) +'</td>';
			rowHtml += '<td><input type="number" style="ime-mode:disabled" class="form-control input-sm concurrentUser" placeholder="并发用户" value="'+ (concurrentUser ? concurrentUser : '0') +'"></td>';
			rowHtml += '<td><input type="number" style="ime-mode:disabled" class="form-control input-sm tps" placeholder="TPS" value="'+ (tps ? tps : '0') +'"></td>';
			rowHtml += '<td><input type="number" style="ime-mode:disabled" class="form-control input-sm responseTime" placeholder="响应时间" value="'+ (responseTime ? responseTime : '0') +'"></td>';
			rowHtml += '<td><input type="number" style="ime-mode:disabled" class="form-control input-sm successReponse" placeholder="成功请求" value="'+ (successReponse ? successReponse : '') +'"></td>';
			rowHtml += '<td><input type="number" style="ime-mode:disabled" class="form-control input-sm errorReponse" placeholder="失败请求" value="'+ (errorReponse ? errorReponse : '') +'"></td>';
			rowHtml += '<td><input type="number" style="ime-mode:disabled" class="form-control input-sm successRate" placeholder="成功率" value="'+ (successRate ? successRate : '0') +'"></td>';
			rowHtml += '<td><textarea class="form-control input-sm remark" rows="1">'+ (remark ? remark : '') +'</textarea></td>';
			rowHtml += '<td><button type="button" class="btn btn-info btn-xs btnCopy">复制</button>&nbsp;<button type="button" class="btn btn-warning btn-xs btnDelete">移除</button></td>';
			rowHtml += '</tr>';

			$('#testRow').append(rowHtml);
		}


		function copyTableRow() {

		}

		function getTableRowValues() {

		}

		function ajaxBeforeSend() {
			layer.load(1, {
			    shade: [0.3,'#000']  
			});
		}

		function ajaxComplete() {
			layer.closeAll('loading');
		}

		function getDateList(date, projectId) {
			if (date && projectId) {
				$.ajax({
	            	type: "GET",
	             	url: "${basePath}chart/dataList",
	             	data: {date : date, projectId : projectId},
	             	dataType: "json",
	             	beforeSend: ajaxBeforeSend(),
	             	complete: ajaxComplete(),
	             	success: function(data){
	             		$('#testRow').html('');

	                	if (data && data.length > 0) {
	                		$.each(data, function(i) { 
	                			addTableRow(data[i].id, data[i].projectId, data[i].projectName, data[i].moduleId, data[i].moduleName, data[i].concurrentUser, data[i].tps, data[i].responseTime, data[i].successRate, data[i].successReponse, data[i].errorReponse, data[i].remark)
	                		})
	                	} else {
	                		$.each(selectModule, function(i) {
								if (selectModule[i].project_id == projectId)  {
									addTableRow(0, projectId, $('#projectId').find("option:selected").text(), selectModule[i].id, selectModule[i].module_name);
								}
							})
	                	}
	         		}
				})
			} else {
				$('#testRow').html('');
			}
		}

		function log(l) {
			console.log(l);
		}

		require.config({
            paths: {
                echarts: '${basePath}asset/dist'
            }
        });
		$(document).ready(function() {
			$.getJSON("${basePath}chart/getModuleList", function(jsonData){ 
				selectModule = jsonData;

				// console.log(selectModule);
			})

			$("#date").datetimepicker({
				format: 'yyyy-mm-dd',
				autoclose: true,
				todayBtn: true,
				language: 'zh-CN',
				minView: 2
			}).on('changeDate', function(ev){ 
				getDateList($("#date").val(), $('#projectId').val());
			});

			$("#projectId").change(function(){ 
				getDateList($("#date").val(), $('#projectId').val());
			})


			$('#btnAddOne').click(function() {
				addTableRow();
			})


			$('#testRow').on('input propertychange', '.successReponse', function() {
				var successReponseVal = $(this).val();
				var errorReponseVal = $(this).parent().parent().find('.errorReponse').val();

				if (!errorReponseVal) errorReponseVal = 0;
				if (!successReponseVal) successReponseVal = 0;
 

				$(this).parent().parent().find('.successRate').val((parseInt(successReponseVal) / (parseInt(errorReponseVal) + parseInt(successReponseVal)) * 100).toFixed(0));
			})

			$('#testRow').on('input propertychange', '.errorReponse', function() {
				var errorReponseVal = $(this).val();
				var successReponseVal = $(this).parent().parent().find('.successReponse').val();

				if (!errorReponseVal) errorReponseVal = 0;
				if (!successReponseVal) successReponseVal = 0; 

				$(this).parent().parent().find('.successRate').val((parseInt(successReponseVal) / (parseInt(errorReponseVal) + parseInt(successReponseVal)) * 100).toFixed(0));
			})

			//限制文本框只能输入数字和小数点
			$('#testRow').on('keyup', '.errorReponse, .successReponse, .responseTime, .concurrentUser, .tps, .successRate', function() {
				$(this).val($(this).val().replace(/[^0-9.]/g,''));  
			})
			$('#testRow').on('paste', '.errorReponse, .successReponse, .responseTime, .concurrentUser, .tps, .successRate', function() {
				$(this).val($(this).val().replace(/[^0-9.]/g,''));      
			})

			//复制
			$('#testRow').on('click', '.btnCopy', function() {
				var nowRow = $(this).parent().parent();
				nowRow.find('.dataId').val('');
				
				$('#testRow').append('<tr>' + nowRow.html() + '</tr>');
			})

			//删除
			$('#testRow').on('click', '.btnDelete', function() {
				var that = $(this);
				layer.confirm('确认要删除吗', {
				    btn: ['确定','取消'], 
				    shade: false  
				}, function(){
					var thatParent = that.parent().parent();
				   	var dataId = thatParent.find('.dataId').val(); 
					if (dataId && dataId != 0) {
						$.ajax({
			            	type: "GET",
			             	url: "${basePath}chart/delete",
			             	data: {dataId : dataId},
			             	dataType: "json",
			             	beforeSend: ajaxBeforeSend(),
			             	complete: ajaxComplete(),
			             	success: function(data){
			             		if (data.status == 200) {
			             			thatParent.remove(); 
			             			layer.closeAll();
			             		} else {
			             			layer.alert(data.message);
			             		}
			         		}
						})
					} else {
						thatParent.remove(); 
						layer.closeAll();
					}
				}, function(){
				    layer.closeAll();
				});
			})

			//保存
			$('#btnSave').click(function() {
				if (!checkDate()) { 
					layer.alert('日期必须输入', {icon: 5});
					return; 
				}

				var listMap = [];

				$('#testRow tr').each(function(i) {
					var dataId = $(this).find('.dataId').val();
					var projectName = $(this).find('.projectName').text();
					var projectId = $(this).find('.projectId').val();
					var moduleName = $(this).find('.moduleName').find("option:selected").text();
					var moduleId = $(this).find('.moduleName').val();
					var concurrentUser = $(this).find('.concurrentUser').val();
					var tps = $(this).find('.tps').val();
					var responseTime = $(this).find('.responseTime').val();
					var successRate = $(this).find('.successRate').val();
					var successReponse = $(this).find('.successReponse').val();
					var errorReponse = $(this).find('.errorReponse').val();
					var remark = $(this).find('.remark').val();

					var map = {
						"dataId" : dataId,
						"projectName" : projectName,
						"projectId" : projectId,
						"moduleName" : moduleName ? moduleName : '',
						"moduleId" : moduleId ? moduleId : '0',
						"concurrentUser" : concurrentUser ? concurrentUser : '0',
						"tps" : tps ? tps : '0',
						"responseTime" : responseTime ? responseTime : '0',
						"successRate" : successRate ? successRate : '0',
						"successReponse" : successReponse,
						"errorReponse" : errorReponse,
						"remark" : remark
					};

					listMap[i] = map;
				})



				var json = JSON.stringify(listMap); 
				if (json) {
					$.ajax({
		            	type: "POST",
		             	url: "${basePath}chart/save",
		             	data: {json : json, date : $("#date").val()},
		             	dataType: "json",
		             	beforeSend: function() {
		             		layer.load(1, {
							    shade: [0.3,'#000']  
							});

							$('#btnSave').attr('disabled',"true");
		             	},
	             		complete: function() {
	             			layer.closeAll('loading');
	             			$('#btnSave').removeAttr("disabled");
	             		},
		             	success: function(data){
		             		if (data.status == 200) {
		             			layer.alert("已保存入库");

		             			getDateList($("#date").val(), $('#projectId').val());
		             		} else {
		             			layer.alert(data.message);
		             		}
		         		}
					})
				}
			})


			$('#btnSaveAndPreview').click(function() {
				if (!checkDate()) { 
					layer.alert('日期必须输入', {icon: 5});
					return; 
				}

				require(
	            [
	                'echarts',
	                'echarts/chart/line',
	                'echarts/chart/bar' // 使用柱状图就加载bar模块，按需加载
	            ],
	            function (ec) { 
	                var myChart = ec.init(document.getElementById('chartDiv'));
	                var option = {
	                	title : {
					        text : '压力测试',
					        subtext : $("#date").val()
					    },
					    tooltip : {
					        trigger: 'axis',
					        axisPointer : {            // 坐标轴指示器，坐标轴触发有效
					            type : 'shadow'        // 默认为直线，可选为：'line' | 'shadow'
					        }
					    },
					    legend: {
					        data:['TPS','响应时间','成功率']
					    },
					    calculable : true,
					    xAxis : [
					        {
					            type : 'category',
					            data : ['项目一']
					        }
					    ],
					    yAxis : [
					        {
					            type : 'value'
					        }
					    ],
					    series : [
					        {
					            name:'TPS',
					            type:'bar',
					            data:[320]
					        },
					        {
					            name:'响应时间',
					            type:'bar', 
					            data:[120]
					        },
					        {
					            name:'成功率',
					            type:'bar', 
					            data:[220]
					        }
					    ]
					}; 

					$.ajax({
		            	type: "GET",
		             	url: "${basePath}chart/echart",
		             	data: {date : $("#date").val()},
		             	dataType: "json",
		             	beforeSend: ajaxBeforeSend(),
	             		complete: ajaxComplete(),
		             	success: function(data){ 
		             		if (data.status == 200) { 
		             			option.xAxis[0].data = data.data.projectName;
		             			option.series = data.data.series;
		             			option.legend.data = data.data.legend; 

		             			myChart.setOption(option); 
		             		} else {
		             			layer.alert(data.message);
		             		}
		         		}
					})

	                
	            })
			})
			    
		})
	</script>


<jsp:include  page="../footer.jsp"/> 